package com.mall.order.services;

import com.mall.order.OrderCoreService;
import com.mall.order.biz.TransOutboundInvoker;
import com.mall.order.biz.context.AbsTransHandlerContext;
import com.mall.order.biz.factory.OrderProcessPipelineFactory;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.constants.OrderConstants;
import com.mall.order.dal.entitys.Order;
import com.mall.order.dal.entitys.OrderItem;
import com.mall.order.dal.entitys.Stock;
import com.mall.order.dal.persistence.OrderItemMapper;
import com.mall.order.dal.persistence.OrderMapper;
import com.mall.order.dal.persistence.OrderShippingMapper;
import com.mall.order.dal.persistence.StockMapper;
import com.mall.order.dto.*;
import com.mall.order.utils.ExceptionProcessorUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

import static com.mall.order.constants.OrderConstants.ORDER_STATUS_PAYED;

/**
 * cskaoyan
 */
@Slf4j
@Component
@Service(cluster = "failfast")
public class OrderCoreServiceImpl implements OrderCoreService {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Autowired
    OrderShippingMapper orderShippingMapper;

    @Autowired
    OrderProcessPipelineFactory orderProcessPipelineFactory;

    @Autowired
    StockMapper stockMapper;


    /**
     * 创建订单的处理流程
     *
     * @param request
     * @return
     */
    @Override
    public CreateOrderResponse createOrder(CreateOrderRequest request) {
        CreateOrderResponse response = new CreateOrderResponse();
        try {
            //创建pipeline对象
            TransOutboundInvoker invoker = orderProcessPipelineFactory.build(request);

            //启动pipeline
            invoker.start(); //启动流程（pipeline来处理）

            //获取处理结果
            AbsTransHandlerContext context = invoker.getContext();

            //把处理结果转换为response
            response = (CreateOrderResponse) context.getConvert().convertCtx2Respond(context);
        } catch (Exception e) {
            log.error("OrderCoreServiceImpl.createOrder Occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }


    @Override
    public PayOrderSuccessResponse payOrderSuccess(PayOrderSuccessRequest request) {

        PayOrderSuccessResponse response = new PayOrderSuccessResponse();

        String orderId = request.getOrderId();

        try {
            request.requestCheck();
            // 2. 修改订单的状态为已支付

            // 根据订单id查询出订单
            Example orderExample = new Example(Order.class);
            orderExample.createCriteria().andEqualTo("orderId", orderId);
            List<Order> orders = orderMapper.selectByExample(orderExample);
            Order order = orders.get(0);

            order.setStatus(OrderConstants.ORDER_STATUS_PAYED);  // 已支付
            order.setUpdateTime(new Date());
            log.info("OrderCoreServiceImpl，修改订单的状态为1已支付：" + order);
            // 修改订单
            orderMapper.updateByExampleSelective(order, orderExample);

            // 3. 修改库存，根据OrderId，查询出所有的订单商品条目，根据每一个商品的数量，扣减锁定库存
            Example orderItemExample = new Example(OrderItem.class);
            orderItemExample.createCriteria().andEqualTo("orderId", orderId);
            List<OrderItem> orderItems = orderItemMapper.selectByExample(orderItemExample);

            for (OrderItem orderItem : orderItems) {
                Long itemId = orderItem.getItemId();
                Integer num = orderItem.getNum();
                // 根据itemId查到锁定库存和实际库存
                Example stockExample = new Example(Stock.class);
                stockExample.createCriteria().andEqualTo("itemId", itemId);
                List<Stock> stocks = stockMapper.selectByExample(stockExample);
                Stock stock = stocks.get(0);
                log.info("OrderCoreServiceImpl，扣减库存前stock：" + stock);
                stock.setLockCount(stock.getLockCount() - num);
                int updateByPrimaryKeyAffectedRows = stockMapper.updateStockAndLockCount(stock);
                log.info("OrderCoreServiceImpl，扣减库存后stock：" + stock + ",updateByPrimaryKeyAffectedRows:" + updateByPrimaryKeyAffectedRows);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("{}"+e);
            response.setCode(OrderRetCode.SYSTEM_ERROR.getCode());
            response.setMsg(OrderRetCode.SYSTEM_ERROR.getMessage());
        }

        response.setCode(OrderRetCode.SUCCESS.getCode());
        response.setMsg(OrderRetCode.SUCCESS.getMessage());
        log.info("OrderCoreServiceImpl.payOrderSuccess,{}",response);
        return response;
    }


}
